<template>
  <div class="app-container paperEdit" style="display: flex; justify-content: center; padding: 32px 66px 41px 66px">
    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules" style="width: 100%">
      <el-form-item label="试卷名称："  prop="name" required>
        <el-input v-model="form.name" placeholder="请选择（或输入）试卷名称"/>
      </el-form-item>
      <el-form-item :key="index" :label="'标题'+(index+1)+'：'" required v-for="(titleItem,index) in form.titleItems">
        <el-input v-model="titleItem.name" style="width: 88%"/>
        <el-button type="text" class="link-left" style="margin-left: 8px; color: #09c214; font-weight: 800; font-size: 0.9rem; margin-left: 16px;" size="mini" @click="addQuestion(titleItem)">
          添加题目
        </el-button>
        <el-popconfirm
          title="确定删除该记录吗？"
          @confirm="form.titleItems.splice(index,1)">
          <el-button type="text" class="link-left" size="mini" slot="reference" style="color: red; margin-left: 10px; font-weight: 800; font-size: 0.9rem">删除</el-button>
        </el-popconfirm>
        <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
          <transition-group name="drag" class="list" tag="ul">
            <li :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"  @dragenter="dragenter($event, questionIndex, titleItem.questionItems, index)" @dragover="dragover($event, questionIndex)" @dragstart="dragstart(questionIndex)" draggable v-for="(questionItem,questionIndex) in titleItem.questionItems"  style="margin-bottom: 15px" class="list-item">
              <el-row>
                <el-col :span="10">{{'题目'+(questionIndex+1)+'：'}}</el-col>
                <el-col :span="20">
                  <QuestionShow :qType="questionItem.questionType" :question="questionItem"/>
                </el-col>
                <el-col :span="1">
                  <el-popconfirm
                    title="确定删除该记录吗？"
                    @confirm="titleItem.questionItems.splice(questionIndex,1)">
                    <el-button type="danger"  slot="reference" size="mini" >删除</el-button>
                  </el-popconfirm>
                </el-col>
              </el-row>
            </li>
          </transition-group>
        </el-card>
      </el-form-item>
      <el-form-item label="考试时长：" prop="suggestTime" required>
        <el-input v-model="form.suggestTime" placeholder="分钟"/>
      </el-form-item>
      <el-form-item style="margin-top: 20px; display: flex; justify-content: center; margin-right: 60px;">
        <el-button plain @click="$router.push('/examination-paper-list')">取消</el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
        <el-button type="success" @click="addTitle">添加标题</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="questionPage.showDialog"  width="70%">
      <el-form :model="questionPage.queryParam" ref="queryForm" :inline="true" style="text-align:center;">
        <!-- <el-form-item label="ID：">
          <el-input v-model="questionPage.queryParam.id"  clearable></el-input>
        </el-form-item> -->
        <el-form-item label="题型：">
          <el-select v-model="questionPage.queryParam.questionType" clearable>
            <el-option v-for="item in questionTypeEnum" :key="item.key" :value="item.key" :label="item.value"
              :title="item.value">
              <span>{{ item.value }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目分类: ">
          <el-autocomplete
            v-model="questionPage.queryParam.category"
            class="inline-input"
            :fetch-suggestions="querySearch2"
            placeholder="请选择（或输入）题目分类"
            style="cursor: pointer"
            @keyup.native="fuzzyqueryJob2($event,input)"
          >
            <template slot-scope="{ item }">
                <a :title="item.value" style="text-decoration:none">{{ item.value }}</a>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item style="margin-bottom: 17px; display: flex; justify-content: center; margin-top: 8px; margin-left: 50px">
          <el-button type="success" @click="queryForm">查询</el-button>
        </el-form-item>
      </el-form>
      <el-form :inline="true" style="text-align: center; display:  flex; flex-direction: column; justify-content: center; align-items: center;">
        <el-table v-loading="questionPage.listLoading" :data="questionPage.tableData" max-height="320px"
                  @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="id" label="Id" width="60px"/>
          <el-table-column prop="questionType" label="题型" :formatter="questionTypeFormatter" width="100px"/>
          <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>
        </el-table>
        <pagination v-show="questionPage.total>0" :total="questionPage.total"
                    :page.sync="questionPage.queryParam.pageIndex" :limit.sync="questionPage.queryParam.pageSize" :pageSizes="[1000, 2000, 5000]"
                    @pagination="search"/>
        <el-form style="margin-top: 40px; margin-left: 40px">
            <el-button @click="questionPage.showDialog = false" style=" margin-right: 6px">取 消</el-button>
            <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
        </el-form>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters, mapState, mapActions } from 'vuex'
import Pagination from '@/components/Pagination'
import QuestionShow from '../question/components/Show'
import examPaperApi from '@/api/examPaper'
import questionApi from '@/api/question'

export default {
  components: { Pagination, QuestionShow },
  data () {
    return {
      originIndex: undefined,
      dragIndex: undefined,
      questionCategoryList: [],
      form: {
        id: null,
        category: null,
        name: '',
        suggestTime: null,
        titleItems: []
      },
      subjectFilter: null,
      formLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入试卷名称', trigger: 'blur' }
        ],
        suggestTime: [
          { required: true, message: '请输入考试时长', trigger: 'blur' }
        ]
      },
      questionPage: {
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          id: null,
          questionType: null,
          category: null,
          pageIndex: 1,
          pageSize: 1000
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      currentTitleItem: null
    }
  },
  created () {
    let id = this.$route.query.id
    let _this = this
    // this.initSubject(function () {
    //   _this.subjectFilter = _this.subjects
    // })
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      examPaperApi.select(id).then(re => {
        _this.form = re.response
        _this.formLoading = false
      })
    }

    this.loadAll()
  },
  methods: {
    dragstart(index) {
      this.originIndex = index;
      this.dragIndex = index;
    },
    dragenter(e, index, list, index0) {
      e.preventDefault();
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const source = list[this.dragIndex];
        this.form.titleItems[index0].questionItems.splice(this.dragIndex, 1);
        this.form.titleItems[index0].questionItems.splice(index, 0, source);
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index;
        console.log('originIndex & afterIndex:', this.originIndex + '  '+ index)
        console.log('this.form.titleItems[index0].questionItems[index]:', this.form.titleItems[index0].questionItems[index])
        console.log('this.form.titleItems[index0].questionItems[this.dragIndex]:', this.form.titleItems[index0].questionItems[this.dragIndex])
        this.form.titleItems[index0].questionItems[this.originIndex].itemOrder = this.originIndex + 1
        this.form.titleItems[index0].questionItems[index].itemOrder = index + 1
        console.log('this.form.titleItems[index0].questionItems:', this.form.titleItems[index0].questionItems)
      }
    },
    dragover(e, index) {
      e.preventDefault();
    },
    loadAll() {
      questionApi.questionCategory().then(res => {
        this.questionCategoryList = res.response
      })
    },
    fuzzyqueryJob2(e, input) {
      if (this.questionPage.queryParam.category !== '' && this.questionPage.queryParam.category !== null && this.questionPage.queryParam.category !== undefined) {
        const jobParam = { keyword: this.questionPage.queryParam.category + '' }
        questionApi.questionCategory(jobParam).then(res => {
          this.questionCategoryList = res.response
        })
      }
    },
    createFilter(queryString) {
      return returnJobs => {
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    querySearch1(queryString, cb) {
      const categorylist = this.paperCategoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    querySearch2(queryString, cb) {
      const categorylist = this.questionCategoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          examPaperApi.edit(this.form).then(re => {
            if (re.code === 1) {
              _this.$message.success(re.message)
              _this.delCurrentView(_this).then(() => {
                // _this.$router.push('/exam/paper/list')
                _this.$router.push('/examination-paper-list')
              })
            } else {
              _this.$message.error(re.message)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    addTitle () {
      this.form.titleItems.push({
        name: '',
        questionItems: []
      })
    },
    addQuestion (titleItem) {
      this.currentTitleItem = titleItem
      this.questionPage.showDialog = true
      this.search()
    },
    removeTitleItem (titleItem) {
      this.form.titleItems.remove(titleItem)
    },
    removeQuestion (titleItem, questionItem) {
      titleItem.questionItems.remove(questionItem)
    },
    queryForm () {
      this.questionPage.queryParam.pageIndex = 1
      this.search()
    },
    confirmQuestionSelect () {
      let _this = this
      this.questionPage.multipleSelection.forEach(q => {
        questionApi.select(q.id).then(re => {
          _this.currentTitleItem.questionItems.push(re.response)
        })
      })
      this.questionPage.showDialog = false
    },
    search() {
      // this.questionPage.queryParam.category = this.form.category
      this.questionPage.listLoading = true
      questionApi.pageList(this.questionPage.queryParam).then(data => {
        const re = data.response
        this.questionPage.tableData = re.list
        this.questionPage.total = re.total
        this.questionPage.queryParam.pageIndex = re.pageNum
        this.questionPage.listLoading = false
      })
    },
    handleSelectionChange (val) {
      this.questionPage.multipleSelection = val
    },
    questionTypeFormatter (row, column, cellValue, index) {
      return this.enumFormat(this.questionTypeEnum, cellValue)
    },
    resetForm () {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: null,
        category: null,
        name: '',
        suggestTime: null,
        titleItems: []
      }
      this.form.id = lastId
    },
    // ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum,
      paperTypeEnum: state => state.exam.examPaper.paperTypeEnum,
      levelEnum: state => state.user.levelEnum
    }),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .paperEdit .exampaper-item-box {
    .q-title {
      margin: 0px 5px 0px 5px;
    }
  }

  .paperEdit .el-autocomplete {
    position: relative;
    display: inline-block;
    width: 100%;
  }

  .paperEdit .el-select {
    display: inline-block;
    position: relative;
    width: 100%;
  }

  .paperEdit .el-form-item {
    margin-bottom: 12px;
  }

  .paperEdit .el-input-number--medium {
    width: 100%;
    line-height: 34px;
  }

  .paperEdit .el-form-item__error {
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 0px;
    position: absolute;
    top: 100%;
    left: 0;
  }

  .paperEdit .el-dialog {
    margin-top: 6vh !important;
  }

  .paperEdit .list {
    list-style: none;
    .drag-move {
      transition: transform 0.3s;
    }
    .list-item {
      cursor: move;
     /* width: 300px;
      background: #EA6E59;
      border-radius: 4px;
      color: #FFF;
      margin-bottom: 6px;
      height: 50px;
      line-height: 50px;
      text-align: center; */
    }
  }
</style>
